package com.demo.common.core.config;

import com.demo.common.base.exception.BaseException;
import com.demo.common.base.pojo.JsonRes;
import com.demo.common.core.util.JsonUtil;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import java.io.Reader;
import java.nio.charset.StandardCharsets;


/**
 * Feign异常传递
 *
 * @author DayDayUp
 * create on 2023-05-25
 **/
@Slf4j
public class FeignErrorDecoder implements ErrorDecoder {
    @Override
    public Exception decode(String s, Response response) {
        BaseException baseException;
        try {
            Reader reader = response.body().asReader(StandardCharsets.UTF_8);
            String string = Util.toString(reader);
            JsonRes<?> jsonRes =JsonUtil.jsonToPojo(string, JsonRes.class);
            baseException = new BaseException(jsonRes.getMsg());
        } catch (Exception e) {
            log.error("处理FeignClient异常错误",e);
            throw new BaseException("处理FeignClient异常错误");
        }
        return baseException;
    }
}
